import fetch from "node-fetch";
import getProxyAgent from "./proxy/getProxyAgent.js";
import cheerio from "cheerio"

// Package API(s) of one user of AtCoder
// Usage:
// const user = new AtCoderUser("wushenghao")
// const res1 = await user.getSubmissionList()               First 500 submissions
// const res2 = await user.getSubmissionList(1710577000)     from 2024-3-16 16:16:40
export default class AtCoderUser {
  constructor(user) {
    this.user = user;
  }

  async getSubmissionList(fromSecond = 0) {
    if (fromSecond === null || fromSecond === undefined) {
      fromSecond = 0;
    }
    let url = `https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions?user=${this.user}&from_second=${fromSecond}`
    const response = await fetch(url, { agent: getProxyAgent() });
    const result = await response.json();
    if (result.length === 0 && fromSecond === 0) {
      throw new Error(`Atcoder user ${this.user} may not exist`);
    }
    return result;
  }

  async getRating() {
    try {
      const url = `https://atcoder.jp/users/${this.user}`;
      const response = await fetch(url, { agent: getProxyAgent() });
      const html = await response.text();
      const $ = cheerio.load(html);


      // 找到Rating字段并提取其值
      const ratingRow = $('th.no-break:contains("Rating")').closest('tr');
      const rating = ratingRow.find('td > span[class^="user-"]').first().text();
      return rating ? rating : 0;
    }
    catch (err) {
      throw new Error(`Atcoder user ${this.user} may not exist or has no rating`);
    }
  }
}
